import { addSysMenus, updateSysMenus } from "@/api/sys/sysMenus";
import { useAppDispatch, useAppSelector } from "@/store";
import {
  get_sys_menus_list,
  get_sys_menus_select_tree,
  select_is_show_menus_modal,
  set_is_show_menus_modal,
} from "@/store/slice/sysMenus";
import { selectDict } from "@/store/slice/app";

import {
  Form,
  Input,
  Modal,
  Select,
  message,
  TreeSelect,
  InputNumber,
} from "antd";
import type { GetProp, TreeSelectProps } from "antd";

import { useEffect, useState } from "react";

type DefaultOptionType = GetProp<TreeSelectProps, "treeData">[number];

function MenusModal() {
  const [formRef] = Form.useForm();
  const [treeData, setTreeData] = useState([] as DefaultOptionType[]);
  const [menuTypeOptions, setMenuTypeOptions] = useState([]);
  const [statusOptions, setStatusOptions] = useState([]);
  const dispatch = useAppDispatch();
  const is_show_data = useAppSelector(select_is_show_menus_modal);
  const allDict = useAppSelector(selectDict);

  if (is_show_data.show && is_show_data.mode === 2) {
    formRef.setFieldsValue(is_show_data.data);
  }

  useEffect(() => {
    dispatch(get_sys_menus_select_tree()).then((res) => {
      setTreeData(initMenusTree(res.payload as SysMenuEntityType[]));
    });
  }, []);

  useEffect(() => {
    const sys_menu_type_options =
      allDict?.sys_menu_type?.map((item: SysDictDataEntity) => {
        return {
          label: item.dictLabel,
          value: item.dictValue,
        };
      }) || [];
    const sys_status_options =
      allDict?.sys_status?.map((item: SysDictDataEntity) => {
        return {
          label: item.dictLabel,
          value: item.dictValue,
        };
      }) || [];
    setMenuTypeOptions(sys_menu_type_options);
    setStatusOptions(sys_status_options);
  }, [allDict]);

  function handleOk() {
    formRef
      .validateFields()
      .then(async (values) => {
        console.log(values);
        // 表单校验通过，执行提交逻辑
        const res =
          is_show_data.mode === 1
            ? await addSysMenus(values)
            : await updateSysMenus({ ...values, id: is_show_data.data.id });
        if (res) {
          message.open({
            type: "success",
            content: "操作成功!",
          });

          dispatch(get_sys_menus_list({}));
          onCancel();
        } else {
          message.open({
            type: "error",
            content: "操作失败!",
          });
        }
      })
      .catch(() => {
        message.open({
          type: "warning",
          content: "请填写完整信息!",
        });
      })
      .finally(() => {});
  }
  function reset() {
    formRef.resetFields();
  }
  function onCancel() {
    reset();
    dispatch(
      set_is_show_menus_modal({
        show: false,
        title: "",
        mode: 1,
        data: {},
      })
    );
  }

  function initMenusTree(data: SysMenuEntityType[]) {
    let list = [] as DefaultOptionType[];
    data.forEach((item) => {
      let temp = {
        value: item.id,
        label: item.name,
        children: [],
      } as DefaultOptionType;
      if (item.children && item.children.length > 0) {
        temp.children = initMenusTree(item.children);
      }
      list.push(temp);
    });
    return list;
  }
  return (
    <Modal
      title={is_show_data.title}
      open={is_show_data.show}
      onOk={handleOk}
      onCancel={onCancel}
    >
      <Form
        form={formRef}
        labelAlign="right"
        labelCol={{ span: 6 }}
        wrapperCol={{ span: 16 }}
      >
        <Form.Item name="pid" label="上级菜单">
          <TreeSelect
            showSearch
            style={{ width: "100%" }}
            dropdownStyle={{ maxHeight: 400, overflow: "auto" }}
            placeholder="请选择上级菜单"
            allowClear
            treeDefaultExpandAll
            treeData={treeData}
          />
        </Form.Item>

        <Form.Item
          name="menuType"
          label="菜单类型"
          rules={[
            {
              required: true,
              message: "请输入菜单类型",
            },
          ]}
        >
          <Select placeholder="菜单类型" allowClear options={menuTypeOptions} />
        </Form.Item>

        <Form.Item name="permissions" label="权限编码">
          <Input placeholder="权限编码" allowClear />
        </Form.Item>
        <Form.Item
          name="name"
          label="菜单名称"
          rules={[
            {
              required: true,
              message: "请输入菜单名称",
            },
          ]}
        >
          <Input placeholder="菜单名称" allowClear />
        </Form.Item>

        <Form.Item name="url" label="菜单地址">
          <Input placeholder="菜单地址" allowClear />
        </Form.Item>
        <Form.Item name="icon" label="菜单图标">
          <Input placeholder="菜单图标" allowClear />
        </Form.Item>

        <Form.Item
          name="status"
          label="状态"
          initialValue={is_show_data.data?.status || "1"}
        >
          <Select placeholder="状态" allowClear options={statusOptions} />
        </Form.Item>

        <Form.Item
          name="sort"
          label="排序号"
          initialValue={is_show_data.data?.sort || 999}
        >
          <InputNumber />
        </Form.Item>
      </Form>
    </Modal>
  );
}
export default MenusModal;
